package com.harmonk.firstscene.ui.model

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.harmonk.firstscene.FirstSceneApplication
import com.harmonk.firstscene.db.entity.QuickNote
import kotlinx.coroutines.launch

class QuickNoteViewModel(application: Application) : AndroidViewModel(application) {
    private val quickNoteRepository = (application as FirstSceneApplication).quickNoteRepository
    
    private val _quickNotes = MutableLiveData<List<QuickNote>>()
    val quickNotes: LiveData<List<QuickNote>> = _quickNotes
    
    private val _currentQuickNote = MutableLiveData<QuickNote>()
    val currentQuickNote: LiveData<QuickNote> = _currentQuickNote
    
    fun loadAllQuickNotes() {
        viewModelScope.launch {
            try {
                quickNoteRepository.getAllQuickNotes().collect { quickNoteList: List<QuickNote> ->
                    _quickNotes.postValue(quickNoteList)
                }
            } catch (e: Exception) {
                // Handle exception
                _quickNotes.postValue(emptyList())
            }
        }
    }
    
    fun getQuickNoteById(id: Long) {
        viewModelScope.launch {
            try {
                val quickNote = quickNoteRepository.getQuickNoteById(id)
                quickNote?.let { q: QuickNote ->
                    _currentQuickNote.postValue(q)
                }
            } catch (e: Exception) {
                // Handle exception
            }
        }
    }
    
    fun insertQuickNote(quickNote: QuickNote): Long {
        var id: Long = -1
        viewModelScope.launch {
            try {
                id = quickNoteRepository.insertQuickNote(quickNote)
            } catch (e: Exception) {
                // Handle exception
            }
        }
        return id
    }
    
    fun updateQuickNote(quickNote: QuickNote) {
        viewModelScope.launch {
            try {
                quickNoteRepository.updateQuickNote(quickNote)
            } catch (e: Exception) {
                // Handle exception
            }
        }
    }
    
    fun deleteQuickNote(quickNote: QuickNote) {
        viewModelScope.launch {
            try {
                quickNoteRepository.deleteQuickNote(quickNote)
            } catch (e: Exception) {
                // Handle exception
            }
        }
    }
}

class QuickNoteViewModelFactory(private val application: Application) : ViewModelProvider.Factory {
    override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(QuickNoteViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return QuickNoteViewModel(application) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}